// 用户认证相关的composable
export const useAuth = () => {
  const token = useCookie("auth_token");
  const user = useCookie("user_info");

  // 登录状态
  const isLoggedIn = computed(() => !!token.value);

  // 当前用户信息
  const currentUser = computed(() => user.value || null);

  // 登录方法
  const login = async (credentials: { username: string; password: string }) => {
    try {
      const response = await $fetch("/api/auth/login", {
        baseURL: "http://localhost:3001",
        method: "POST",
        body: credentials,
      });

      if (response.success) {
        // 保存token和用户信息
        token.value = response.data.token;
        user.value = response.data.user;

        ElMessage.success("登录成功");
        return { success: true };
      } else {
        ElMessage.error(response.message || "登录失败");
        return { success: false, message: response.message };
      }
    } catch (error: any) {
      console.error("登录失败:", error);
      const message =
        error.response?.data?.message || "登录失败，请检查用户名和密码";
      ElMessage.error(message);
      return { success: false, message };
    }
  };

  // 登出方法
  const logout = () => {
    token.value = null;
    user.value = null;
    navigateTo("/login");
    ElMessage.success("已退出登录");
  };

  // 检查权限
  const hasPermission = (permission: string) => {
    if (!currentUser.value?.roles) return false;

    // 这里应该根据用户的角色权限进行检查
    // 暂时简化处理
    return true;
  };

  // 检查角色
  const hasRole = (role: string) => {
    if (!currentUser.value?.roles) return false;

    return currentUser.value.roles.some((r: any) =>
      typeof r === "string" ? r === role : r.name === role
    );
  };

  return {
    // 状态
    isLoggedIn,
    currentUser,
    token,
    user,

    // 方法
    login,
    logout,
    hasPermission,
    hasRole,
  };
};
